package com.kuang.service.Impl;

import com.kuang.entity.SecurityUser;
import com.kuang.entity.User;
import com.kuang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service("UserDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名从数据库查询到该用户的信息
        User user = userService.selectByUsername(username);
        // 没有查询到用户
        if (Objects.isNull(user)){
            throw new UsernameNotFoundException("当前用户不存在");
        }
        // 根据用户名从数据库查询到该用户的权限信息
        SecurityUser securityUser = new SecurityUser();
        // 设置用户信息
        securityUser.setCurrentUserInfo(user);
        String[] list = user.getUse_role().split(",");
        List<String> useRole = new ArrayList<>();
        for (String s : list) {
            useRole.add(s);
        }
        // 设置用户权限
        securityUser.setPermissionValueList(useRole);
        return securityUser;
    }
}
